package com.project.service.impl;

import com.project.config.MinioConfig;
import com.project.service.MinioService;
import com.project.utils.MinioUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;

/**
 * @description: 存储实现类
 **/
@Service
public class MinioServiceImpl implements MinioService {

    @Resource
    private MinioUtils minioUtils;
    @Resource
    private MinioConfig minioConfig;

    @Override
    public boolean bucketExists(String bucketName) {
        return minioUtils.bucketExists(bucketName);
    }

    @Override
    public void makeBucket(String bucketName) {
        minioUtils.makeBucket(bucketName);
    }

    @Override
    public boolean putObject(String objectName, InputStream stream, String contentType) {
        String bucketName = getBucketName();
        return minioUtils.putObject(bucketName, objectName, stream, contentType);
    }

    @Override
    public boolean removeObject(String objectName) {
        String bucketName = getBucketName();
        return minioUtils.removeObject(bucketName, objectName);
    }

    @Override
    public void downloadFile(String fileName, HttpServletResponse response) {
        String bucketName = getBucketName();
        minioUtils.downloadFile(bucketName, fileName, response);
    }

    /**
     * 获取预览地址
     *
     * @param objectName 存储桶里的对象名称
     * @return 获取预览地址
     */
    @Override
    public String presignedGetObject(String objectName) {
        String bucketName = getBucketName();
        return minioUtils.presignedGetObject(bucketName, objectName, 7 * 24 * 3600);
    }

    /**
     * 获取bucketName
     *
     * @return bucketName
     */
    private String getBucketName() {
        String bucketName = minioConfig.getBucketName();
        if (!this.bucketExists(bucketName)) {
            this.makeBucket(bucketName);
        }
        return bucketName;
    }
}
